package com.musiclibrary.scraper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.musiclibrary.common.JsoupUtils;
import com.musiclibrary.persistence.MusicCategory;

public class TelguScraper implements MusicScraper {

	private WebPage<Map<String, String>> webPage;

	public TelguScraper() {

	}

	public TelguScraper(WebPage<Map<String, String>> webPage) {
		this.webPage = webPage;
		initWebPage(this.webPage);
	}

	public WebPage<Map<String, String>> getWebPage() {
		return webPage;
	}

	public void setWebPage(WebPage<Map<String, String>> webPage) {
		this.webPage = webPage;
		initWebPage(this.webPage);
	}

	private void initWebPage(final WebPage<Map<String, String>> webPage) {
		webPage.setFormHandler(new FormHandler<Map<String, String>>() {

			public void updateForm(Map<String, String> data) {
				webPage.getHtmlForm().setFromParameters(data);
			}
		});
	}

	/*
	 * This method read site data
	 */
	public List<MusicCategory> loadPage() {
		List<MusicCategory> musicCategories = null;
		try {
			if (getWebPage() != null) {
				Document document = new JsoupUtils().loadPage(getWebPage());
				if (document != null) {
					musicCategories = parseDocument(document);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return musicCategories;
	}

	private List<MusicCategory> parseDocument(Document document) {
		List<MusicCategory> musicCategories = null;
		try {
			MusicCategoryParser musicCategoryParser = new MusicCategoryParser();
			Elements categoryElements = document.select("body div.listMenu");
			if (categoryElements != null && categoryElements.size() > 0) {
				musicCategories=new ArrayList<MusicCategory>();
				for (Element element : categoryElements) {
					MusicCategory musicCategory = musicCategoryParser.parseMusicCategory(element, getWebPage());
					musicCategories.add(musicCategory);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return musicCategories;
	}
}
